# -*- coding:utf-8 -*-
#2022/1/16 8:51
# author:xwl
import math

from fastapi import APIRouter, Depends

from backend.app.app.api.api_Xiong.crud.pri_crud import get_proj_ID_by_userid
from backend.app.app.api.api_Xiong.crud.pub_crud import db_fuc1, read_oilprod_cost, read_oilsalecost_ratio, \
    eva_cal_save_data, planproj_oilprodcost, planproj_oilsalecost_ratio, forecast_delete_result
from backend.app.app.api.api_Xiong.models.x_model import dvp_cal_read, eva_cal_save, eva_cal_calculation
from backend.app.app.api.api_v1.user import verify_token_user
from backend.app.app.api.calculation.evaluation_calculation import wellOprCost, grossSalesIncome, totalTax, staticGains, \
    staticGainsPy, evaluation_calculation5, evaluation_calculation6, evaluation_calculation7, evaluation_calculation8, \
    evaluation_calculation9, evaluation_calculation10
from backend.app.app.api.effect_pridict.base_infomation import return_tree
from backend.app.app.crud_pub.tb_project_message import get_name, get_stim_type, get_all_year, \
    plan_name_and_dvpname_and_stimtype

eva_cal_input = APIRouter(prefix="/eva_cal_input", tags=["单元方案评价指标计算输入数据"])

@eva_cal_input.post("/get_datas",name="获取方案名称、开发单元、措施类别、年度")
async def get_datas(ver=Depends(verify_token_user)):
    dvpunit_name, stim_type, year=plan_name_and_dvpname_and_stimtype()
    # d_data, plan_infs = get_name()
    # dvpunit_name = return_tree(d_data, None)
    # stim_type=get_stim_type()
    # year=get_all_year()
    return {
        'Dvp_Unit': dvpunit_name if dvpunit_name else {},
        'StimType':stim_type,
        'Year':year,
        #'Stim_Plan':plan_infs,
        'verify': ver
    }

@eva_cal_input.post("/read",name="读库")
async  def read(datas:dvp_cal_read,ver=Depends(verify_token_user)):
    result_data1 = db_fuc1(datas.planproj_name,datas.dvpunit_name,datas.year,datas.stimtype_name)
    oilprod_cost = read_oilprod_cost(datas.planproj_name,datas.dvpunit_name,datas.year)
    oilsalecost_ratio = read_oilsalecost_ratio(datas.planproj_name,datas.dvpunit_name,datas.year)
    return {
        'mix_inf':result_data1,
        'oilprod_cost':oilprod_cost,
        'oilsalecost_ratio':oilsalecost_ratio,
        'verify': ver
    }

@eva_cal_input.post("/get_proj_ID",name="获取现有的Proj_ID")
async  def get_proj_ID(userid:str,ver=Depends(verify_token_user)):
    proj_id=get_proj_ID_by_userid(userid)
    return {
        "proj_id":proj_id,
        'verify': ver
    }

@eva_cal_input.post("/save",name="存库")
async  def save(datas: eva_cal_save, ver=Depends(verify_token_user)):
    planproj_forecast_delete_result = forecast_delete_result(datas.delete)
    eva_cal_save_result = eva_cal_save_data(datas.datas)
    planproj_oilprodcost_result = planproj_oilprodcost(datas.oilcost)
    planproj_oilsalecost_ratio_result = planproj_oilsalecost_ratio(datas.ratio)
    return {
        'eva_cal_save_result': eva_cal_save_result,
        'planproj_oilprodcost_result': planproj_oilprodcost_result,
        'planproj_oilsalecost_ratio_result': planproj_oilsalecost_ratio_result,
        'planproj_forecast_delete_result': planproj_forecast_delete_result,
        'verify': ver
    }

@eva_cal_input.post("/calculation",name="计算")
async  def calculation(datas:eva_cal_calculation,ver=Depends(verify_token_user)):
    result = []
    try:
        temp1 = dict()
        for data in datas.datas:
            # 1.计算平均增油操作成本
            WellOprCost = wellOprCost(IncreOil=float(data["Stim_IncreOil_Average"]), OilOprCost=float(data["Oil_OprCost"]))

            # 2.计算平均增油毛收入
            GrossSalesIncome = grossSalesIncome(OilPrice=float(data["Oil_Price"]),
                                                OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                IncreOil=float(data["Stim_IncreOil_Average"]))

            # 3.计算平均销售税费
            TotalTax = totalTax(GrossSalesIncome=GrossSalesIncome, TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))

            # 4.平均静态收益（元/井）：StaticGains
            StaticGains = staticGains(StimCost=float(data["Stim_Cost"]), WellOprCost=WellOprCost, TotalTax=TotalTax,
                                      GrossSalesIncome=GrossSalesIncome)

            # 5.平均财务净现值（元/井）：StimNPV
            # ValidPeriod = 123 #有效天  未找到，临时使用
            # 直接计算StaticGainsPy, 后续需要使用
            ValidPeriod = int(data["Stim_ValidPeriod_Average"])
            ValidYears = math.ceil(ValidPeriod / 365)
            ic = float(data["Money_Discount"]) / 100
            StaticGainsPy_by_count = staticGainsPy(IncreOil=float(data["Stim_IncreOil_Average"]), ValidYears=ValidYears,
                                                   OilPrice=float(data["Oil_Price"]),
                                                   OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                   TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]),
                                                   OilOprCost=float(data["Oil_OprCost"]))
            StimNPV = evaluation_calculation5(ValidYears=ValidYears, StaticGainsPy=StaticGainsPy_by_count, ic=ic,
                                              StimCost=float(data["Stim_Cost"]))

            # 6.投资利润率（%）：StimROI
            StimROI = evaluation_calculation6(StaticGains=StaticGains, StimCost=float(data["Stim_Cost"]))

            # 7.财务净现值率（%）：
            StimNPVR = evaluation_calculation7(StimNPV=StimNPV, StimCost=float(data["Stim_Cost"]))

            # 8.财务内部收益率（%）：StimFIRR
            # ValidPeriod = data["Stim_ValidPeriod_Average"]
            # ValidYears = math.ceil(ValidPeriod / 365)
            StimFIRR = evaluation_calculation8(ValidYears=ValidYears, StimCost=float(data["Stim_Cost"]),
                                               StaticGainsPy=StaticGainsPy_by_count)

            # 9.平均经济临界增油量（吨/井）：IncreOilCritical
            # ic = data["Money_Discount"]/100
            IncreOilCritical = evaluation_calculation9(ValidYears=ValidYears, ic=ic, StimCost=float(data["Stim_Cost"]),
                                                       OilPrice=float(data["Oil_Price"]),
                                                       OilOprCost=float(data["Oil_OprCost"]),
                                                       OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                       TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))

            # 10.平均经济临界油价（元/吨）：OilPriceCritical
            increOilPy = float(data["Stim_IncreOil_Average"]) / ValidYears
            OilPriceCritical = evaluation_calculation10(ValidYears=ValidYears, ic=ic, StimCost=float(data["Stim_Cost"]),
                                                        IncreOilPy=increOilPy, OilOprCost=float(data["Oil_OprCost"]),
                                                        OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                        TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))
            # 把所有处理完的数据添加到结果
            temp1 = {
                'User_ID': data['User_ID'],
                'Proj_ID': data['Proj_ID'],
                'DvpUnit_OilStim_PlanProj_Name': data['DvpUnit_OilStim_PlanProj_Name'],
                'DvpUnit_Name': data['DvpUnit_Name'],
                'Year': data['Year'],
                'StimType_Name': data['StimType_Name'],
                'Forecast_Method': data['Forecast_Method'],
                'Stim_WellValidRatio': data['Stim_WellValidRatio'],
                'Oil_OprCost': data['Oil_OprCost'],
                'OilSale_TotalTaxRatio': data['OilSale_TotalTaxRatio'],
                'Stim_WellNumber_Valid': data['Stim_WellNumber_Valid'],
                'Stim_ValidPeriod_Average': data['Stim_ValidPeriod_Average'],
                'Stim_IncreOil_Average': data['Stim_IncreOil_Average'],
                'Update_Date': data['Update_Date'],
                'Stim_Cost': data['Stim_Cost'],
                'Oil_CommodityRatio': data['Oil_CommodityRatio'],
                'Oil_Price': data['Oil_Price'],
                'Money_Discount': data['Money_Discount'],
                'Remark': data['Remark'],
                "WellOprCost": WellOprCost,
                "TotalTax": TotalTax,
                "GrossSalesIncome": GrossSalesIncome,
                "StaticGains": StaticGains,
                "StimNPV": StimNPV,
                "StimROI": StimROI,
                "StimNPVR": StimNPVR,
                "StimFIRR": StimFIRR,
                "IncreOilCritical": IncreOilCritical,
                "OilPriceCritical": OilPriceCritical
            }
            result.append(temp1)
        return {
            'result': result if result else {},
            'verify': ver
        }
    except Exception as e:
        print(e)
        return {
            'result': None,
            'verify': ver
        }